﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LinkCard.Model;
using LinkCard.Dao;
using LinkCard.AdminCP.Common;
using System.Data;
using System.Text;

namespace LinkCard.AdminCP.CRM
{
    public partial class customers_new : System.Web.UI.Page
    {
        protected Int64 nCustomerID;
        protected Int64 nOldCustomerID;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["USER"] == null)
            {
                Response.Redirect("/login.aspx");
            }

            if (!IsPostBack)
            {
                //GetShop();
                //Điền ngày hết hạn

                this.ExpiredDate.Value = DateTime.Now.Day.ToString() + "/" + DateTime.Now.Month.ToString() + "/" + DateTime.Now.AddYears(1).Year.ToString();
                //Random pass
                this.Password.Value = RandomString(6).ToString();

                if (Request.QueryString["CustomerID"] != null)
                {
                    nOldCustomerID = ConvertUtility.ToInt64(Request.QueryString["CustomerID"]);
                    LoadForCreateNew(nOldCustomerID);
                }

            }
           
        }

        protected void btnPublish_Click(object sender, EventArgs e)
        {
            addCustormer(1);
            addCustormerTemp();
            if (Request.QueryString["CustomerID"] != null)
            {
                nOldCustomerID = ConvertUtility.ToInt64(Request.QueryString["CustomerID"]);
                DeleteCustomerRegFromHome(nOldCustomerID);
            }
            
            Response.Redirect("/message_box.aspx?why=1&msg=1");
        }

        //protected void btnAdd_Click(object sender, EventArgs e)
        //{
        //    addCustormer(0);
        //    addCustormerTemp();
        //    if (Request.QueryString["CustomerID"] != null)
        //    {
        //        nOldCustomerID = ConvertUtility.ToInt64(Request.QueryString["CustomerID"]);
        //        DeleteCustomerRegFromHome(nOldCustomerID);
        //    }
        //    Response.Redirect("/message_box.aspx?why=1&msg=1");
        //}

        protected void addCustormer(byte status) {
            var dao = new CustomerDao();
            
            System.Globalization.DateTimeFormatInfo dateInfo = new System.Globalization.DateTimeFormatInfo();
            dateInfo.ShortDatePattern = "dd/MM/yyyy";
            
            var _cus = new Customer();
            _cus.Address = Address.Value;

            _cus.Birthday = Convert.ToDateTime(Birthday.Value, dateInfo);
            
            _cus.Email = Email.Value;
            _cus.Fullname = Fullname.Value;
            _cus.CardNumber = CardNumber.Value;
            _cus.Gender = Convert.ToByte(Gender.SelectedItem.Value);
            _cus.ID = ID.Value;
            _cus.Income = Convert.ToDecimal((Income.Value == "")? "0" : Income.Value);
            _cus.Job = Job.Value;
            _cus.MobilePhone = MobilePhone.Value;
            _cus.OtherInfo = OtherInfo.Value;
            //Mã hóa mật khẩu
            var tempPass = Utils.EncryptPass.Encrypt(Password.Value, CardNumber.Value);
            _cus.Password = tempPass;
            //tempPass = Utils.EncryptPass.Decrypt(tempPass, CardNumber.Value);
            _cus.Point = 0;
            _cus.RegisterDate = DateTime.Now;
            _cus.SystemRegister = Convert.ToByte(SystemRegister.SelectedItem.Value);
            _cus.TransactionAmount = 0;
            //_cus.Username = Username.Value;
            _cus.Status = status;
            if (!ckNoExpiredDate.Checked)
            {
                _cus.ExpiredDate = Convert.ToDateTime(ExpiredDate.Value, dateInfo);
                
            }
            _cus.VietnamAirlineGLPNumber = VietnamAirlineGLPNumber.Value;
            _cus.CardLevel = Convert.ToByte(CardLevel.Value);
            dao.Add(_cus);
            nCustomerID = _cus.CustomerID;

            //if (!string.IsNullOrEmpty(_cus.Tags))
            //{
            //    var addTag = new TagDao().AddDealTag(_cus.CustomerID, _cus.Tags);
            //}
 
        }

        protected void addCustormerTemp()
        {
            var dao = new CustomerTempDao();
            
            System.Globalization.DateTimeFormatInfo dateInfo = new System.Globalization.DateTimeFormatInfo();
            dateInfo.ShortDatePattern = "dd/MM/yyyy";
            
            var _cus = new CustomerTemp();
            _cus.Address = Address.Value;
            
            _cus.Birthday = Convert.ToDateTime(Birthday.Value, dateInfo);
            
            _cus.Email = Email.Value;
            _cus.Fullname = Fullname.Value;
            _cus.CardNumber = CardNumber.Value;
            _cus.Gender = Convert.ToByte(Gender.SelectedItem.Value);
            _cus.ID = ID.Value;
            _cus.Income = Convert.ToDecimal(Income.Value == "" ? "0" : Income.Value);
            _cus.Job = Job.Value;
            _cus.MobilePhone = MobilePhone.Value;
            _cus.OtherInfo = OtherInfo.Value;
            //Mã hóa mật khẩu
            var tempPass = Utils.EncryptPass.Encrypt(Password.Value, CardNumber.Value);
            _cus.Password = tempPass;

            _cus.Point = 0;
            _cus.RegisterDate = DateTime.Now;
            _cus.SystemRegister = Convert.ToByte(SystemRegister.SelectedItem.Value);
            _cus.TransactionAmount = 0;
            //_cus.Username = Username.Value;
            _cus.Status = 1;
            _cus.DateLog = DateTime.Now;
            _cus.UserID = getUserID();
            _cus.CustomerID = nCustomerID;
            _cus.VietnamAirlineGLPNumber = VietnamAirlineGLPNumber.Value;
            _cus.CardLevel = Convert.ToByte(CardLevel.Value);

            if (!ckNoExpiredDate.Checked)
            {
                _cus.ExpiredDate = Convert.ToDateTime(ExpiredDate.Value, dateInfo);

            }

            dao.Add(_cus);
        }

        protected Int64 getUserID()
        {

            DataTable dt = DataHelper.SelectTable("SELECT UserID FROM [User] WHERE Username ='" + Session["USER"].ToString() + "'", false);
            if (dt.Rows.Count > 0)
            {
                return ConvertUtility.ToInt64(dt.Rows[0]["UserID"]);
            }
            else
            {
                return 0;
            }
        }

        [System.Web.Services.WebMethod]
        public static bool CheckUserName(string sUsername)
        {
            string sSQL = "SELECT Username FROM Customer WHERE Username = N'" + sUsername + "'";
            DataTable dt = DataHelper.SelectTable(sSQL, false);
            if (dt.Rows.Count > 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        [System.Web.Services.WebMethod]
        public static bool CheckCardNumber(string sCardNumber)
        {
            string sSQL = "SELECT Username FROM Customer WHERE CardNumber = N'" + sCardNumber + "'";
            DataTable dt = DataHelper.SelectTable(sSQL, false);
            if (dt.Rows.Count > 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        private void GetShop()
        {
            //SupplierDao _supplierDao = new SupplierDao();
            //List<LinkCard.Model.Supplier> _supplierList = _supplierDao.GetAll();

            //foreach (LinkCard.Model.Supplier _supplier in _supplierList)
            //{
            //    if (_supplier.SupplierID.ToString().Length == 1)
            //        ddlShop.Items.Insert(0, new ListItem(_supplier.Name.ToString(), "00" + _supplier.SupplierID.ToString()));
            //    else if (_supplier.SupplierID.ToString().Length == 2)
            //        ddlShop.Items.Insert(0, new ListItem(_supplier.Name.ToString(), "0" + _supplier.SupplierID.ToString()));
            //    else if (_supplier.SupplierID.ToString().Length == 0)
            //        ddlShop.Items.Insert(0, new ListItem(_supplier.Name.ToString(), "000"));
            //    else if (_supplier.SupplierID.ToString().Length == 3)
            //        ddlShop.Items.Insert(0, new ListItem(_supplier.Name.ToString(), "" + _supplier.SupplierID.ToString()));
            //}
            
        }

        private void LoadForCreateNew(Int64 nCustomerID)
        {
            if (nCustomerID > 0)
            {
                string sSQL = "";
                
                sSQL = "SELECT * FROM Customer WHERE CustomerID =" + nCustomerID.ToString() + "";
                btnPublish.Visible = true;

                DataTable dtCustomer = DataHelper.SelectTable(sSQL, false);
                if (dtCustomer.Rows.Count > 0)
                {

                    Address.Value = dtCustomer.Rows[0]["Address"].ToString();

                    Email.Value = dtCustomer.Rows[0]["Email"].ToString();

                    Fullname.Value = dtCustomer.Rows[0]["Fullname"].ToString();

                    MobilePhone.Value = dtCustomer.Rows[0]["MobilePhone"].ToString();

                    if (dtCustomer.Rows[0]["CityID"].ToString().Length < 2)
                        city.Value = "0" + dtCustomer.Rows[0]["CityID"].ToString();
                    else
                        city.Value = dtCustomer.Rows[0]["CityID"].ToString();

                    SystemRegister.SelectedIndex = 0;

                    VietnamAirlineGLPNumber.Value = dtCustomer.Rows[0]["VietnamAirlineGLPNumber"].ToString();
                }
            }
        }

        private void DeleteCustomerRegFromHome(Int64 nCustomerID)
        {
            try
            {
                string sSQL = "delete customer where CustomerID =" + nCustomerID.ToString();
                DataHelper.ExecuteNonQuery(sSQL, true);
            }
            catch
            {
 
            }
        }

        private static Random random = new Random((int)DateTime.Now.Ticks);//thanks to McAden
        private string RandomString(int size)
        {
            StringBuilder builder = new StringBuilder();
            char ch;
            for (int i = 0; i < size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }

            return builder.ToString().ToLower();
        }
    }
}